package com.itheima.dao;

import com.github.pagehelper.Page;
import com.itheima.pojo.Menu;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Set;

public interface MenuDao {

    @Select("select * from t_user where username=#{username}")
    @Results({
            @Result(property = "id",column = "id"),
            @Result(property = "roles",column = "id",many=@Many(select = "com.itheima.dao.RoleDao.findRoleWithPermissionByUserId"))
    })
    User findUserWithPermissionByUsername(String username);

    @Select("select * from t_user where username=#{username}")
    @Results({
            @Result(property = "id",column = "id"),
            @Result(property = "roles",column = "id",many=@Many(select = "com.itheima.dao.RoleDao.findRoleWithMenuByUserId"))
    })
    User findUserWithMenuByUsername(String username);

    /*@Select("<script>select * from t_user <if test=\"queryString!=null and queryString!=''\">where username=#{queryString}</if></script>")
    Page<UserShow> findByCondition(@Param("queryString") String queryString);*/

    @Insert("insert into t_user(birthday,gender,username,password,remark,station,telephone) values(#{birthday},#{gender},#{username},#{password},#{remark},#{station},#{telephone})")
    @SelectKey(statement = "select last_insert_id()",before=false,keyProperty = "id",resultType = Integer.class,keyColumn = "id")
    void add(User user);

    @Insert("insert into t_user_role(user_id,role_id) values(#{userId},#{roleId})")
    void setUserAndRole(@Param("userId") Integer userId,@Param("roleId") Integer roleId);

    @Select("select * from t_user where id=#{id}")
    User findById(Integer id);

    @Select("select role_id from t_user_role where user_id=#{id}")
    List<Integer> findRoleIdsByUserId(Integer id);

    @Update("update t_user set birthday=#{birthday},gender=#{gender},username=#{username},password=#{password},remark=#{remark},station=#{station},telephone=#{telephone} where id=#{id}")
    void edit(User user);

    @Delete("delete from t_user_role where user_id=#{id}")
    void deleteAssociation(Integer id);

    @Delete("delete from t_user where id=#{id}")
    void deleteById(Integer id);

    @Select("<script>select * from t_menu  where hasChildren='true' <if test=\"queryString!=null and queryString!=''\">and name=#{queryString}</if></script>")
    Page<Menu> selectByCondition(@Param("queryString") String queryString);

    @Select("select * from t_menu where parentMenuId=#{id}")
    Set<Menu> findByParentMenuId(Integer id);

    @Select("select * from t_menu where id in (select menu_id from t_role_menu where role_id=#{roleId})")
    @Results({
            @Result(property = "id",column = "id"),
            //根据查询出来的menu表的id字段进行后续子查询
            @Result(property = "children",column = "id",many=@Many(select="com.itheima.dao.MenuDao.findByParentMenuId"))
    })
    Set<Menu> findAllParentMenu(Integer roleId);
}
